//发送用户上线通知
function SendUserOnLine() {
    var userid = $("#now_user_zid").val();
    var username = $("#now_user_name").val(); 
    //创建JSON对象
    var msgObj = {
        fromuserid: userid,
        fromusername: username,
        command_type: 'user_on_line'
    };
    //发送消息
    ws.send(JSON.stringify(msgObj));
}

/**
 * 刷新消息列表
 */
function RefreshMessagesList() {
    var session_userid = $("#now_user_zid").val();
    $.ajax({
        type: "GET",
        url: 'GetUserMessageList?touserid=' + session_userid,
        success: function (data) {
            if (data.code == 'SUCCESS') {
                $('#UserMessagesList').empty();
                var messages_length = data.data.length;
                for (var i = 0; i < messages_length; i++) {
                    var messageinfo = data.data[i];
                    var userid = messageinfo.zid;
                    if (session_userid != userid) {
                        var username = messageinfo.user_name;
                        if (messageinfo.messagecount > 0) {
                            username = username + '[' + messageinfo.messagecount + ']';
                        }
                        var buttoncss = 'btn btn-light btn-block';
                        if (messageinfo.isonline == 0) {
                            buttoncss = 'btn btn-success btn-block';
                        }
                        var button_html = '<button id="message_user_' + userid + '" type="button" class="' + buttoncss + '" onclick="OpenMessageWindows(\'' + userid + '\',\'' + messageinfo.user_name + '\')">' + username + '</button>';
                        $('#UserMessagesList').append(button_html);
                    }
                }

            }
        }
    });
}





/**
 * 根据信息类型，显示不同信息形态
 * @param r_text
 */
function printMsgText(r_text){
    var text = "";
    var r = $.parseJSON(r_text);
    var userid = $("#now_user_zid").val();
    var fromuserid = r.data.fromuserid;
    var fromusername = decodeURIComponent(r.data.fromusername);
    var touserid = r.data.touserid;
    var tousername = decodeURIComponent(r.data.tousername);
    var command_type = r.data.command_type;
    var msgtype = r.data.msgtype;
    var msg = decodeURIComponent(r.data.msg);
    var sendtime = r.data.sendtime;

    if ('usertouser' == command_type) {
        if(msgtype === 'img'){
            text = '<img src="'+msg+'" onclick="lookupImg2(\''+msg+'\')" class="img-thumbnail">';
        }else{
            text = msg;
        }
    }else if ('audio_apply' == command_type) {
        if(userid===fromuserid){
            text = "您已经向"+tousername+"发起语音通话请求，连接中";
        }else if(userid===touserid){
            text = fromusername+"请求与您进行语音通话。";
            text = text +'<button type="button" onclick="audio_apply_yes(\''+fromuserid+'\')" class="btn btn-link">同意</button>,';
            text = text +'<button type="button" onclick="audio_apply_no(\''+fromuserid+'\')" class="btn btn-link">不同意</button>';
        }else{
            text = "发起语音通话异常";
        }
    }else if ('video_apply' == command_type){
        if(userid===fromuserid){
            text = "您已经向"+tousername+"发起视频通话请求，连接中";
        }else if(userid===touserid){
            text = fromusername+"请求与您进行视频通话。"
            text = text +'<button type="button" onclick="video_apply_yes(\''+fromuserid+'\')" class="btn btn-link">同意</button>,';
            text = text +'<button type="button" onclick="video_apply_no(\''+fromuserid+'\')" class="btn btn-link">不同意</button>';
        }else{
            text = "发起视频通话异常";
        }
    }else if ('audio_apply_no' == command_type){
        if(userid===fromuserid){
            text = "您拒绝了"+tousername+"的通话申请。"
        }else if(userid===touserid){
            text = fromusername+"拒绝了您的通话申请";
        }
    }else if ('video_apply_no' == command_type){
        if(userid===fromuserid){
            text = "您拒绝了"+tousername+"的视频申请。"
        }else if(userid===touserid){
            text = fromusername+"拒绝了您的视频申请";
        }
    }else if ('audio_apply_yes' == command_type){
        if(userid===fromuserid){
            text = "您同意了"+tousername+"的通话申请。"
        }else if(userid===touserid){
            text = fromusername+"同意了您的通话申请";
        }
    }else if ('video_apply_yes' == command_type){
        if(userid===fromuserid){
            text = "您同意了"+tousername+"的视频申请。"
        }else if(userid===touserid){
            text = fromusername+"同意了您的视频申请";
        }
    }else{
        text = msg;
    }
    return text;
}

/**
 * 显示消息
 */
function printMsg(r_text) {
    if (isNotNull(r_text)) {
        var r = $.parseJSON(r_text);
        var userid = $("#now_user_zid").val();
        var fromuserid = r.data.fromuserid;
        var fromusername = decodeURIComponent(r.data.fromusername);
        var touserid = r.data.touserid;
        var tousername = decodeURIComponent(r.data.tousername);
        var command_type = r.data.command_type;
        var msgtype = r.data.msgtype;
        var msg = decodeURIComponent(r.data.msg);
        var sendtime = r.data.sendtime;


        //保存聊天记录到Cookie
        var message_cookieid = 'message_cookieid_' + fromuserid + '_' + touserid;
        var message_cookie_obj = {
            fromuserid: fromuserid,
            fromusername: fromusername,
            touserid: touserid,
            tousername: tousername,
            sendtime: sendtime,
            msg: msg
        };
        var old_message_cookie = getCookie(message_cookieid);
        var new_message_cookie = old_message_cookie + '☆' + JSON.stringify(message_cookie_obj);
        setCookie(message_cookieid, new_message_cookie);


        //判读聊天窗口是否打开
        var isopen = $('#message_windows').parent().css('display');
        if (isopen == 'none') {
            //未打开

            //发送右下角消息提醒
            if (userid == touserid) {
                var msgHTML = '		<div class="msgbox">';
                msgHTML = msgHTML + '			<div class="msgboxhead1">' + fromusername + ' ' + sendtime + '</div>';
                msgHTML = msgHTML + '			<div class="msgboxtext">' + printMsgText(r_text) + '</div>';
                msgHTML = msgHTML + '		</div>';
                alertMessager('<a href="javascript:void(0);" onclick="OpenMessageWindows(\'' + fromuserid + '\',\'' + fromusername + '\')">' + msgHTML + '</a>');
            }

            //更新用户头像后面消息数量
            UpdateMessageCount(fromuserid);

        }


        //将消息显示在对应 用户消息框中
        if (userid == fromuserid) {
            //创建消息
            var msgHTML = '		<div class="msgbox">';
            msgHTML = msgHTML + '			<div class="msgboxhead1">' + fromusername + ' ' + sendtime + '</div>';
            msgHTML = msgHTML + '			<div class="msgboxtext">' + printMsgText(r_text) + '</div>';
            msgHTML = msgHTML + '		</div>';
            $('#msgboxlist_' + touserid).append(msgHTML);

            //控制滚动条到最底部
            var scrollHeight = $('#msgboxlist_' + touserid).prop("scrollHeight");
            $('#msgboxlist_' + touserid).animate({scrollTop: scrollHeight}, 400);
        } else {

            //判读是否已经建立了发信人消息框
            if (!$('#MessageTab').tabs('exists', fromusername)) {
                var tabHTML = '<div class="easyui-layout" data-options="fit:true">';
                tabHTML = tabHTML + '	<div id="msgboxlist_' + fromuserid + '" data-options="region:\'center\'" style="padding:10px;">';
                tabHTML = tabHTML + '	</div>';
                tabHTML = tabHTML + '	<div data-options="region:\'south\',split:true" style="position:relative;margin: 0px;padding: 0px;height: 150px;">';
                tabHTML = tabHTML + '		<textarea id="msg_' + fromuserid + '" style="width: 100%;height: 100%;resize:none;border:none;"></textarea>';
                tabHTML = tabHTML + '		<button class="btn btn-light " onclick="OpenGetImg()" style="position:absolute;left:5px;bottom:5px;"><i class="fa fa-image"></i></button>';
                tabHTML = tabHTML + '		<button class="btn btn-light " onclick="AudioCall()" style="position:absolute;left:45px;bottom:5px;"><i class="fa fa-phone"></i></button>';
                tabHTML = tabHTML + '		<button class="btn btn-light" onclick="VideoCall()" style="position:absolute;left:85px;bottom:5px;"><i class="fa fa-video-camera"></i></button>';
                tabHTML = tabHTML + '		<button class="btn btn-light" onclick="sendMessage()" style="position:absolute;right:20px;bottom:5px;"><i class="fa fa-send-o"></i> 发送</button>';
                tabHTML = tabHTML + '	</div>';
                tabHTML = tabHTML + '</div>';

                $('#MessageTab').tabs('add', {
                    title: fromusername,
                    id: fromuserid,
                    content: tabHTML
                });

                //$('#MessageTab').tabs('select', fromusername);
            } else {
                var tab = $('#MessageTab').tabs('getSelected');
                var title = tab.panel('options').title;
                if (fromusername != title) {
                    //更新用户头像后面消息数量
                    UpdateMessageCount(fromuserid);
                }
            }

            //创建消息
            var msgHTML = '		<div class="msgbox">';
            msgHTML = msgHTML + '			<div class="msgboxhead0">' + fromusername + ' ' + sendtime + '</div>';
            msgHTML = msgHTML + '			<div class="msgboxtext">' + printMsgText(r_text) + '</div>';
            msgHTML = msgHTML + '		</div>';
            $('#msgboxlist_' + fromuserid).append(msgHTML);

            //控制滚动条到最底部
            var scrollHeight = $('#msgboxlist_' + fromuserid).prop("scrollHeight");
            $('#msgboxlist_' + fromuserid).animate({scrollTop: scrollHeight}, 400);
        }
    }
}


//更新用户头像后面消息数量
function UpdateMessageCount(fromuserid) {
    $.ajax({
        type: "GET",
        async: true, //true为异步方法 false为同步方法
        url: 'getFromuserMessageCount?fromuserid=' + fromuserid,
        success: function (data) {
            if (data.code == 'SUCCESS') {
                $('#message_user_' + fromuserid).text(data.data);
            }
        },
        error: function (data) {
            parent.alertErrorMessager('ajax错误：' + data);
        }
    });
}

/**
 * 执行发送
 */
function RunSend(obj){
    if(ws.readyState===1){
        ws.send(JSON.stringify(obj));
    }else{
        console.log(ws);
        init_socket();
        if(ws.readyState===1){
            ws.send(JSON.stringify(obj));
        }else{
            alertErrorMessager('与通信服务连接已断开，无法发送信息给服务器')
        }

    }
}

/**
 * 用户发送信息
 */
function sendMessage() {
    var fromuserid = $("#now_user_zid").val();
    var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    var msg = encodeURIComponent($('#msg_' + touserid).val());
    var msgtype = '0';//0是文本消息

    //创建JSON对象
    var msgObj = {
        fromuserid: fromuserid,
        touserid: touserid,
        command_type: 'usertouser',
        msgtype: msgtype,
        msg: msg
    };

    //发送消息
    RunSend(msgObj);


    //保存已发送消息到cookie
    var message_cookieid = 'message_cookieid_' + touserid + '_' + fromuserid;
    var fromusername = $("#now_user_name").val();
    var sendtime = getDateTime();
    var message_cookie_obj = {
        fromuserid: fromuserid,
        fromusername: fromusername,
        touserid: touserid,
        sendtime: sendtime,
        msg: msg
    };
    var old_message_cookie = getCookie(message_cookieid);
    var new_message_cookie = old_message_cookie + '☆' + JSON.stringify(message_cookie_obj);
    setCookie(message_cookieid, new_message_cookie);


    //请空已发送信息
    $('#msg_' + touserid).val('');
    $('#msg_' + touserid).focus();

}

/**
 * 获取系统时间
 * @returns {string}
 */
function getDateTime() {
    var myDate = new Date();
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    var date = myDate.getDate(); //获取当前日
    var h = myDate.getHours();//获取当前小时数(0-23)
    var m = myDate.getMinutes();//获取当前分钟数(0-59)
    var s = myDate.getSeconds();//获取当前秒
    return year + "-" + mon + "-" + date + " " + h + ":" + m + ":" + s;
}

/**
 * 打开聊天窗口
 */
function OpenMessageWindows(fromuserid, fromusername) {
    $('#fromuserid').val('${zuser.zid}');
    $('#touserid').val(fromuserid);

    if (!$('#MessageTab').tabs('exists', fromusername)) {
        var tabHTML = '<div class="easyui-layout" data-options="fit:true">';
        tabHTML = tabHTML + '	<div id="msgboxlist_' + fromuserid + '" data-options="region:\'center\'" style="padding:10px;">';
        tabHTML = tabHTML + '	</div>';
        tabHTML = tabHTML + '	<div data-options="region:\'south\',split:true" style="position:relative;margin: 0px;padding: 0px;height: 150px;">';
        tabHTML = tabHTML + '		<textarea id="msg_' + fromuserid + '" style="width: 100%;height: 80%;resize:none;border:none;outline:none;margin-top:0px;margin-bottom:0px;"></textarea>';
        tabHTML = tabHTML + '		<button class="btn btn-light " onclick="OpenGetImg()" style="position:absolute;left:5px;bottom:5px;"><i class="fa fa-image"></i></button>';
        tabHTML = tabHTML + '		<button class="btn btn-light " onclick="AudioCall()" style="position:absolute;left:45px;bottom:5px;"><i class="fa fa-phone"></i></button>';
        tabHTML = tabHTML + '		<button class="btn btn-light" onclick="VideoCall()" style="position:absolute;left:85px;bottom:5px;"><i class="fa fa-video-camera"></i></button>';
        tabHTML = tabHTML + '		<button class="btn btn-light" onclick="sendMessage()" style="position:absolute;right:20px;bottom:5px;"><i class="fa fa-send-o"></i> 发送</button>';
        tabHTML = tabHTML + '	</div>';
        tabHTML = tabHTML + '</div>';

        $('#MessageTab').tabs('add', {
            title: fromusername,
            id: fromuserid,
            content: tabHTML
        });
    } else {
        $('#MessageTab').tabs('select', fromusername);
    }

    //设置焦点
    $('#msg_' + fromuserid).focus();

    //修改消息是否查看状态为以查看
    UpdateIsOpen(fromuserid, fromusername);


    //判读指定用户聊天窗口是首着次打开，如果是首次打开，加载cookie中的历史信息到当前窗口
    var touserid = $("#now_user_zid").val();
    var message_cookieid = 'message_cookieid_' + fromuserid + '_' + touserid;
    if ($('#msgboxlist_' + fromuserid).children().length == 0) {
        var old_message_cookie = getCookie(message_cookieid);
        var messageArray = old_message_cookie.split('☆');
        for (var i = 0; i < messageArray.length; i++) {
            var message_r_text = messageArray[i];
            if (isNotNull(message_r_text)) {
                var r = $.parseJSON(message_r_text);
                var fromusername = r.fromusername;
                var msg = r.msg;
                var sendtime = r.sendtime;
                if (isNotNull(fromusername)) {
                    //创建消息
                    var msgHTML = '		<div class="msgbox">';
                    if (touserid == r.fromuserid) {
                        msgHTML = msgHTML + '			<div class="msgboxhead1">' + fromusername + ' ' + sendtime + '</div>';
                    } else {
                        msgHTML = msgHTML + '			<div class="msgboxhead0">' + fromusername + ' ' + sendtime + '</div>';
                    }

                    msgHTML = msgHTML + '			<div class="msgboxtext">' + msg + '</div>';
                    msgHTML = msgHTML + '		</div>';
                    $('#msgboxlist_' + fromuserid).append(msgHTML);
                }

            }

        }
    }

    //直接Open不显示新消息，需要动一下窗口，就能显示，怀疑这块是一个easyui的bug
    $('#message_windows').window('open');//打开窗口
    $('#message_windows').window('collapse');//折叠
    $('#message_windows').window('expand');//展开

}

//修改消息是否查看状态为以查看
function UpdateIsOpen(fromuserid, fromusername) {
    $.ajax({
        type: "get",
        async: true, //true为异步方法 false为同步方法
        url: 'UpdateIsOpen?fromuserid=' + fromuserid,
        success: function (data) {
            if (data.code == 'SUCCESS') {
                $('#message_user_' + fromuserid).text(fromusername);
            }
        },
        error: function (data) {
            parent.alertErrorMessager('ajax错误：' + data);
        }
    });
}

/**
 * 关闭聊起页
 */
function CloseMessageWindows(touserid, tousername) {
    $('#MessageTab').tabs('close', tousername);
    var tab = $('#MessageTab').tabs('getSelected');
    var index = $('#MessageTab').tabs('getTabIndex', tab);
    if (index < 0) {
        //关闭windows窗口
        $('#message_windows').window('close');
    }
}

/**
 * 打开图片选择页面
 * @constructor
 */
function OpenGetImg(){
    var width = 400;
    var height = 250;
    var iTop = (window.screen.availHeight - 30 - height) / 2;//获得窗口的垂直位置;
    var iLeft = (window.screen.availWidth - 10 - width) / 2;//获得窗口的水平位置;
    var url = 'im_getimg';
    window.open(url, '文件上传', 'width=' + width + ',height=' + height + ',location=no,menubar=no,status=no,toolbar=no, top=' + iTop + ', left=' + iLeft);
}

/**
 *
 * @constructor
 */
function SendImg(urls){
    var userid = $("#now_user_zid").val();
    var username = $("#now_user_name").val();
    var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    //创建JSON对象
    var msgObj = {
        fromuserid: userid,
        fromusername: username,
        touserid:touserid,
        command_type: 'usertouser',
        msgtype:'img',
        msg:urls
    };
    //发送消息
    ws.send(JSON.stringify(msgObj));
}

/**
 * 即时通讯发起语音通话
 */
function AudioCall(){
    //启动本地视频
    OpenLocalVideoCallBox(false,false,'');
    //申请视频通话
    SendMassage('audio_apply','');
    var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    console.log('您申请与'+touserid+'进行语音通话');
}

/**
 * 即时通讯发起视频通话
 */
function VideoCall(){
    //启动本地视频
    OpenLocalVideoCallBox(false,false,'');
    //申请视频通话
    SendMassage('video_apply','');
    var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    console.log('您申请与'+touserid+'进行视频通话');
}


/**
 * 打开本地视频采集窗口
 * @constructor
 */
function OpenLocalAudioCallBox(isCreateRTCPeerConnection,isAddStream){
    var isopen = $('#local_call_windows').parent().css('display');
    if (isopen == 'none') {
        //未打开
        $('#local_call_windows').window('open');//打开窗口
        $('#local_call_windows').window('collapse');//折叠
        $('#local_call_windows').window('expand');//展开
    }

    //采集音视频设备数据,采集音频与视频，视频格式为320*600 试用于手机
    OpenUserMedia(true,false,isCreateRTCPeerConnection,isAddStream,messageType);

}

/**
 * 打开本地视频采集窗口
 * @constructor
 */
function OpenLocalVideoCallBox(isCreateRTCPeerConnection,isAddStream,messageType){
    var local_call_windows_isopen = $('#local_call_windows').parent().css('display');
    if (local_call_windows_isopen == 'none') {
        //未打开
        $('#local_call_windows').window('open');//打开窗口
        $('#local_call_windows').window('collapse');//折叠
        $('#local_call_windows').window('expand');//展开
    }

    //采集音视频设备数据,采集音频与视频，视频格式为320*600 试用于手机
    OpenUserMedia(true,{width: 320, height: 600 },isCreateRTCPeerConnection,isAddStream,messageType);
}

/**
 * 打开用户音视频设备
 * audio:json/boolean 是否采集音频
 * video:json/boolean 是否采集视频 示例：{width: 320, height: 600 } 手机
 * isAddStream:是否同步推流
 */
function OpenUserMedia(audio,video,isCreateRTCPeerConnection,isAddStream,messageType){
    var userid = $("#now_user_zid").val();
    //var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    var getUserMedia = navigator.getUserMedia;
    if(isNotNull(getUserMedia)){
        var constraints = { audio: audio, video: video};
        navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) {
            //本地流
            localStream = mediaStream;

            //是否同步创建链接
            if(isCreateRTCPeerConnection){
                console.log(userid+'开始建立连接');
                CreateRTCPeerConnection(isAddStream,messageType);
            }

            //将流显示出来
            var localvideo = document.querySelector('video#localvideo');
            localvideo.srcObject = mediaStream;


        }).catch(function(err) {
            console.log('采集音视频设备信息出错');
            console.log(err);
        });
    }else{
        console.log('浏览器不支持视频通话');
    }
}


//同意语音通话
function audio_apply_yes(fromuserid){
    //启动本地视频
    OpenLocalAudioCallBox(true,true,'audio_apply_yes');

}

//拒绝语音通话
function audio_apply_no(fromuserid){
    var userid = $("#now_user_zid").val();
    var username = $("#now_user_name").val();
    //创建JSON对象
    var msgObj = {
        fromuserid: userid,
        fromusername: username,
        touserid:fromuserid,
        command_type: 'audio_apply_no',
        msg:encodeURIComponent(username+'拒绝了您的通话申请')
    };
    //发送消息
    ws.send(JSON.stringify(msgObj));
}

//同意视频通话
function video_apply_yes(fromuserid){
    //启动本地视频
    OpenLocalVideoCallBox(true,true,'video_apply_yes');
}

//拒绝视频通话
function video_apply_no(fromuserid){
    var userid = $("#now_user_zid").val();
    var username = $("#now_user_name").val();
    //创建JSON对象
    var msgObj = {
        fromuserid: userid,
        fromusername: username,
        touserid:fromuserid,
        command_type: 'video_apply_no',
        msg:encodeURIComponent(username+'拒绝了您的视频申请')
    };
    //发送消息
    ws.send(JSON.stringify(msgObj));
}


/**
 * Createpc
 * @constructor
 * isAddStream 是否同步推流
 */
function CreateRTCPeerConnection(isAddStream,messageType){
    var userid = $("#now_user_zid").val();
    var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    console.log('发起人：'+userid+' | 接收人：'+touserid+'   | 方法名：CreateRTCPeerConnection');

    var config = {};
    var iceServers = [];
    var iceserver = {};
    iceserver.urls = $("#ice_url").val();
    iceserver.credential = $("#ice_username").val();
    iceserver.user = $("#ice_password").val();
    iceServers.push(iceserver);
    config.iceServers = iceServers;

    // var pcConfig = {
    //     'iceServers':[{
    //         'urls':'stun:coturn.merroix.com:3478',
    //         'credential':'merro',
    //         'user':'Merro1234'
    //     }]
    // }
    var iceServers = [];

    //创建连接
    pc = new RTCPeerConnection(config);

    //是否直接推送流
    if(isAddStream){
        //将本地流向远程推送
        console.log('发起人：'+userid+' - 开始推流');
        localStream.getTracks().forEach(track => {
            console.log(userid+'-推送视频流')
            pc.addTrack(track,localStream);
        });
    }

    //是否发送指令
    if(isNotNull(messageType)){
        SendMassage(messageType,'');
    }

    //向远端发送信息
    pc.onicecandidate = (e)=>{
        if(e.candidate){
            console.log("fromuser:"+userid+" 收到STUN服务器回调|e.candidate="+e.candidate);
            //发送信息给接收端
            var msg = {
                type:'candidate',
                label:e.candidate.sdpMLineIndex,
                id:e.candidate.sdpMid,
                candidate: e.candidate.candidate
            };
            SendMassage("webrtc_candidate",msg);
        }
    }

    //接收对方视频流，显示出来
    var remotevideo = document.querySelector('video#remotevideo');
    pc.ontrack = (e)=>{
        remotevideo.srcObject =  e.streams[0];
    }
}


/**
 * 创建协商信息
 */
function createOffer(offerToRecieveAudio,offerToRecieveVideo,command_type){
    var userid = $("#now_user_zid").val();
    var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    console.log('发起人：'+userid+' | 接收人：'+touserid+'   | 方法名：创建createOffer');

    if(pc){
        //创建协商信息
        var offerOptions= {
            offerToRecieveAudio:offerToRecieveAudio,
            offerToRecieveVideo:offerToRecieveVideo
        }
        pc.createOffer(offerOptions).then(function (desc){
            console.log('根据Offer执行setLocalDescription')
            pc.setLocalDescription(desc)
            // console.log('createOffer==>desc');
            // console.log(desc);
            offer = desc.toJSON();
            //发送视频通话请求,包括offer协商信息
            SendMassage(command_type,offer);
        }).catch(function (err){
            console.log("创建视频协商信息出错");
            console.log(err);
        });
    }
}

function createAnswer(offerToRecieveAudio,offerToRecieveVideo,command_type){
    var userid = $("#now_user_zid").val();
    var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    console.log('发起人：'+userid+' | 接收人：'+touserid+'   | 方法名：创建createAnswer');
    pc.createAnswer().then(function (desc){
        console.log('根据Answer执行setLocalDescription')
        pc.setLocalDescription(desc);
        // console.log('createAnswer==>desc');
        // console.log(desc);
        //发送协商信息
        SendMassage(command_type,desc);
    }).catch(function (err){
        console.error('错误的协商信息');
        console.error(err);
    })
}




/**
 * 发送协商信息
 * @param desc
 * @constructor
 */
function SendMassage(command_type,desc){
    var userid = $("#now_user_zid").val();
    var username = $("#now_user_name").val();
    var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    //创建JSON对象
    var msgObj = {
        fromuserid: userid,
        fromusername: username,
        touserid:touserid,
        command_type: command_type,
        msg:desc
    };
    //发送消息
    ws.send(JSON.stringify(msgObj));
}


/**
 * 关闭RTCPeerConnection
 */
function closeRTCPeerConnection(){
    var userid = $("#now_user_zid").val();
    var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
    console.log('发起人：'+userid+' | 接收人：'+touserid+'   | 方法名：关闭RTCPeerConnection');
    if(pc){
        pc.close();
        pc = null;
    }
}

/**
 * 结束视频
 */
function call_windows_close(isSendCommand){
    if(isSendCommand){
        //发送结束视频命令
        SendMassage("video_close","");
    }

    //关闭本地视频流
    var localvideo = document.querySelector('video#localvideo');
    if(isNotNull(localvideo)){
        var localvideo_stream = localvideo.srcObject;
        if(isNotNull(localvideo_stream)){
            var localvideo_tracks = localvideo_stream.getTracks();
            if(isNotNull(localvideo_tracks)){
                for (const track of localvideo_tracks) {
                    track.stop();
                }
                localvideo.srcObject = null;
                localStream = null;
            }
        }
    }

    //关闭远程视频流
    var remotevideo = document.querySelector('video#remotevideo');
    if(isNotNull(remotevideo)){
        var remotevideo_stream = remotevideo.srcObject;
        if(isNotNull(remotevideo_stream)){
            var remotevideo_tracks = remotevideo_stream.getTracks();
            if(isNotNull(remotevideo_tracks)){
                for (const track of remotevideo_tracks) {
                    track.stop();
                }
                remotevideo.srcObject = null;
                remoteStream = null;
            }
        }
    }

    //关闭连接
    closeRTCPeerConnection();

    //关闭窗口
    $('#local_call_windows').window('close');
}